package comp5511.project04;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BPlusTree {

	private Node root;

	private int order;

	private Node head;

	public Node getHead() {
		return head;
	}

	public void setHead(Node head) {
		this.head = head;
	}

	public Node getRoot() {
		return root;
	}

	public void setRoot(Node root) {
		this.root = root;
	}

	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	public Object get(String key) {
		return root.get(key);
	}

	public void remove(String key) {
		root.remove(key, this);

	}

	public void insertOrUpdate(String key, Object obj) {
		root.insertOrUpdate(key, obj, this);

	}

	public BPlusTree(int order) {
		if (order < 3) {
			System.out.print("order must be greater than 2");
			System.exit(0);
		}
		this.order = order;
		root = new Node(true, true);
		head = root;
	}

	public void index(String inputFile) throws Exception{
		BufferedReader reader = null;
		try{
			reader = new BufferedReader(new FileReader(inputFile));
			String line;
			int number=0;
			while (((line = reader.readLine()) != null)) {
				number++;
				if(number==1){
					continue;
				}
				String[] strArray = line.split("\\|");
				String pid = strArray[1].trim();
				String title = strArray[2].trim();
				String[] authors = strArray[3].trim().split(";");
				String[] keywords = strArray[4].trim().split(",");
				String path = strArray[5].trim();
				Paper paper = new Paper(pid, title, authors, keywords, path);
				for(String author: authors){
					insertOrUpdate(author, paper);
				}
			}
			System.out.println("indexing finished");
		}
		catch(Exception e){
			System.out.println("fail when creating index");
			throw e;
		}
		finally{
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}